<template>
  <div :class="{fullscreen:fullscreen}" class="tinymce-container editor-container">
    <textarea :id="tinymceId" class="tinymce-textarea"/>
    <div class="editor-custom-btn-container">
      <editorImage color="#1890ff" class="editor-upload-btn" @successCBK="imageSuccessCBK"/>
      <div>
        <el-upload
            :multiple="false"
            :show-file-list="false"
            :on-success="handleSuccess"
            :action="CMBASE.baseUploadAction">
          <!--          <el-button size="mini" type="primary" icon="el-icon-upload"> word导入</el-button>-->
        </el-upload>
      </div>
    </div>

    <div class="editor-custom-btn-container">

    </div>


  </div>
</template>

<script>
import editorImage from './components/editorImage'
import plugins from './plugins'
import toolbar from './toolbar'
import axios from 'axios'

export default {
  name: 'Tinymce',
  components: {editorImage},
  props: {
    id: {
      type: String,
      default: function () {
        return 'vue-tinymce-' + new Date() + ((Math.random() * 1000).toFixed(0) + '')
      }
    },
    value: {
      type: String,
      default: ''
    },
    toolbar: {
      type: Array,
      required: false,
      default() {
        return []
      }
    },
    menubar: {
      type: String,
      default: 'file edit insert view format table'
    },
    height: {
      type: Number,
      required: false,
      default: 360
    }
  },
  data() {
    return {
      hasChange: false,
      hasInit: false,
      tinymceId: this.id,
      fullscreen: false,
      languageTypeList: {
        'zh': 'zh_CN',
        'en': 'en',
      }
    }
  },
  computed: {
    language() {
      return this.languageTypeList['zh']
    }
  },
  watch: {
    value(val) {
      if (!this.hasChange && this.hasInit) {
        this.$nextTick(() =>
            window.tinymce.get(this.tinymceId).setContent(val || ''))
      }
    },
    language() {
      this.destroyTinymce()
      this.$nextTick(() => this.initTinymce())
    }
  },
  beforeDestroy() {
    this.destroyTinymce()
  },
  mounted() {
    this.initTinymce()
  },
  activated() {
    this.initTinymce()
  },
  deactivated() {
    this.destroyTinymce()
  },
  destroyed() {
    this.destroyTinymce()
  },
  methods: {

    handleSuccess(response, file) {
      console.log(response)

      let config = {headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}};
      let url = 'http://127.0.0.1:4002/CM-API/convertPdf/docToHtml';
      console.log(url)
      //上传文件
      axios.get(url + "?docPath=" + response.path, {docPath: response.path}, config).then((response) => {
        console.log(response);

        const _this = this

        window.tinymce.get(_this.tinymceId).insertContent(response.data.data)

      });


    },

    initTinymce() {
      const _this = this
      window.tinymce.init({
        // 强制回车键换行 不是加段落
        forced_root_block: 'p',
        // 行高
        lineheight_formats: '1 1.5 2 2.5 3 2.5 4 4.5 5',
        language: this.language,
        selector: `#${this.tinymceId}`,
        height: this.height,
        body_class: 'panel-body ',
        object_resizing: false,
        toolbar: this.toolbar.length > 0 ? this.toolbar : toolbar,
        menubar: this.menubar,
        plugins: plugins,
        end_container_on_empty_block: true,
        powerpaste_word_import: 'propmt',
        powerpaste_html_import: 'propmt',
        powerpaste_allow_local_images: true,
        paste_data_images: true,
        // 富文本尺寸编辑
        toolbar_sticky: true,
        autosave_ask_before_unload: false,
        // 开启图片上传
        automatic_uploads: true,
        images_upload_url: '',
        fontsize_formats: "8pt 10pt 12pt 14pt 16pt 18pt 20pt 22pt 24pt 36pt",
        font_formats: "微软雅黑='Microsoft YaHei';苹方='PingFang SC';宋体='SimSong';黑体='SimHei';华文仿宋='华文仿宋';楷体='Kai';Andale Mono=andale mono,times;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;Comic Sans MS=comic sans ms,sans-serif;Courier New=courier new,courier;Georgia=georgia,palatino;Helvetica=helvetica;Impact=impact,chicago;Symbol=symbol;Tahoma=tahoma,arial,helvetica,sans-serif;Terminal=terminal,monaco;Times New Roman=times new roman,times;Trebuchet MS=trebuchet ms,geneva;Verdana=verdana,geneva;Webdings=webdings;Wingdings=wingdings",

        code_dialog_height: 450,
        code_dialog_width: 1000,
        advlist_bullet_styles: 'square',
        advlist_number_styles: 'default',
        imagetools_cors_hosts: ['www.tinymce.com', 'codepen.io'],
        default_link_target: '_blank',
        link_title: false,
        nonbreaking_force_tab: true, // inserting nonbreaking space &nbsp; need Nonbreaking Space Plugin
        init_instance_callback: editor => {
          if (_this.value) {
            editor.setContent(_this.value)
          }
          _this.hasInit = true
          editor.on('NodeChange Change KeyUp SetContent', () => {
            this.hasChange = true
            this.$emit('input', editor.getContent())
          })
        },
        setup(editor) {
          editor.on('FullscreenStateChanged', (e) => {
            _this.fullscreen = e.state
          })
        },
        media_live_embeds: true,
        // file_picker_callback（文件上传回调）
        file_picker_callback: function (cb, value, meta) {
          // callback：上传成功后执行的回调函数，此函数是由TinyMCE定义的，它的第一个参数是上传结果，第二个参数可以是一个object，其中定义了要填入对话框中的字段键值。
          // value：当前受影响的字段值
          // meta：为一个包含指定对话框中其它字段值的对象（meta.filetype是当前对话框的文件类型）
          console.log('当前传输的文件类型', meta.filetype);
          //创建一个隐藏的type=file的文件选择input
          let input = document.createElement('input');
          input.setAttribute('type', 'file');
          input.onchange = function () {
            let file = this.files[0];//只选取第一个文件。如果要选取全部，后面注意做修改
            console.log(file);

            let formData = new FormData();
            formData.append("file", file);
            let config = {headers: {'Content-Type': 'multipart/form-data'}};


            let uploadUrl = _this.CMBASE.baseUploadAction;
            let baseFileContext = _this.CMBASE.baseFileContext;

            console.log('富文本传图接口名称', uploadUrl)
            //上传文件
            axios.post(uploadUrl, formData, config).then((response) => {
              console.log('富文本传图接口', response);
              if (response.data.state === 'success') {
                let path = baseFileContext + response.data.path;
                cb(path, {title: file.name, alt: file.name, width: '100%', height: 'auto'});
                // cb(path, {title: file.name, alt: file.name, width: 'auto', height: 'auto'});
                console.log('富文本传图成功', uploadUrl)
              }
            });
          }
          //触发点击
          input.click();
        }
      })
    },
    destroyTinymce() {
      const tinymce = window.tinymce.get(this.tinymceId)
      if (this.fullscreen) {
        tinymce.execCommand('mceFullScreen')
      }
      if (tinymce) {
        tinymce.destroy()
      }
    },
    setContent(value) {
      window.tinymce.get(this.tinymceId).setContent(value)
    },
    getContent() {
      window.tinymce.get(this.tinymceId).getContent()
    },
    imageSuccessCBK(arr) {
      const _this = this
      arr.forEach(v => {
        window.tinymce.get(_this.tinymceId).insertContent(`<img class="wscnph" src="${v.url}" width="100%" height="auto">`)
      })
    }
  }
}
</script>

<style scoped>
.tinymce-container {
  position: relative;
}

.tinymce-container >>> .mce-fullscreen {
  z-index: 10000;
}

.tinymce-textarea {
  visibility: hidden;
  z-index: -1;
}

.editor-custom-btn-container {
  position: absolute;
  right: 4px;
  top: 4px;
  z-index: 2005;
  display: flex;
}

.fullscreen .editor-custom-btn-container {
  z-index: 10000;
  position: fixed;
}

.editor-upload-btn {
  display: inline-block;
  margin-right: 5px;
}
</style>
<style>
/* 在el-dialog中tinymce z-index 被太小而被遮挡时要加这两句 */
.tox-tinymce-aux {
  z-index: 99999 !important;
}

.tinymce.ui.FloatPanel {
  z-Index: 99;
}
</style>
